package com.cg.offer;

import org.junit.Test;

import java.util.*;

/**
 * @program: LeetCode->Offer_38
 * @description: 剑指Offer 38.字符串的排列
 * @author: cg
 * @create: 2022-04-05 16:07
 **/
public class Offer_38 {

    @Test
    public void test38() {
        System.out.println(Arrays.toString(permutation("abc")));
    }

    /**
     * 输入一个字符串，打印出该字符串中字符的所有排列。
     * <p>
     * 你可以以任意顺序返回这个字符串数组，但里面不能有重复元素。
     * <p>
     * 示例:
     * 输入：s = "abc"
     * 输出：["abc","acb","bac","bca","cab","cba"]
     *  
     * 限制：
     * 1 <= s 的长度 <= 8
     *
     * @param s
     * @return
     */
    public String[] permutation(String s) {
        char[] stack = new char[s.length()];
        int top = -1;
        boolean[] visited = new boolean[s.length()];
        List<String> res = new ArrayList<>();
        dep(stack, top, s, visited, res);
        return res.toArray(new String[0]);
    }

    void dep(char[] stack, int top, String s, boolean[] visited, List<String> res) {
        if (top == s.length() - 1) {
            res.add(new String(stack));
            return;
        }
        Map<Character, Integer> hisMap = new HashMap<>();
        for (int i = 0; i < s.length(); i++) {
            if (visited[i]) {
                continue;
            }
            if (hisMap.size() != 0 && hisMap.get(s.charAt(i)) != null) {
                continue;
            }
            visited[i] = true;
            stack[++top] = s.charAt(i);
            dep(stack, top, s, visited, res);
            visited[i] = false;
            hisMap.put(stack[top--], 1);
        }
    }

    /*List<String> res = new LinkedList<>();
    char[] c;

    public String[] permutation(String s) {
        c = s.toCharArray();
        dfs(0);
        return res.toArray(new String[0]);
    }

    void dfs(int x) {
        if (x == c.length - 1) {
            // 添加排列方案
            res.add(String.valueOf(c));
            return;
        }
        HashSet<Character> set = new HashSet<>();
        for (int i = x; i < c.length; i++) {
            // 重复，因此剪枝
            if (set.contains(c[i])) {
                continue;
            }
            set.add(c[i]);
            // 交换，将 c[i] 固定在第 x 位
            swap(i, x);
            // 开启固定第 x + 1 位字符
            dfs(x + 1);
            // 恢复交换
            swap(i, x);
        }
    }

    void swap(int a, int b) {
        char tmp = c[a];
        c[a] = c[b];
        c[b] = tmp;
    }*/

}
